﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CWB.Web.MVC.Filters;
using CWB.Common.Constant;
using CWB.Web.MVC.BaseController;
using CWB.Common.Logging;
using CWB.Web.Models.Configuration;
using CWB.WebSite.Models.Voice;
using CWB.Web.DB;
using CWB.Web.Models;
using CWB.Common.DTO;
using CWB.Web.Configuration;
using CWB.Common.Utilities;
using System.Net;
using CWB.Web.Misc;

namespace CWB.WebSite.Controllers.Service
{
    [PermissionFilterAttvibute(loginType = LoginType.Bo)]
    public class VoiceServiceController : MultiCultureBaseController
    {
        private static readonly ISysLog Log = SysLog.GetLogger(typeof(BouServiceController));

        public VoiceServiceController(LanguageInfo languageInfo)
            : base(languageInfo)
        {
            ControllerPermision = Permission.Private;
        }


        // GET: /VoiceService/
        [HttpPost]
        public JsonResult Create(string chtWord, string descript, string example, string voiceWord, int categorySn)
        {
            DbTableVoice o = new DbTableVoice();
            ResultBase result = new ResultBase();

            DbModelVoice VoiceModel = new DbModelVoice()
            {
                sn = 0,
                chtWord = chtWord,
                status = 0,
                descript = descript,
                example = example,
                voiceWord = voiceWord,
                CategorySn = categorySn
            };

            if (o.CheckWordIsExist(VoiceModel.chtWord))
            {
                result.Message = Localization.TrandlateMessage(Err.ChineseWordExisting);
            }
            else
            {
                if (o.createData(VoiceModel))
                {
                    result.Message = Localization.TrandlateMessage(Msg.CreateVoiceDataSuccess);
                    result.Result = ReturnCode.Success;
                    Log.Debug("Create Voice data success, Chinese Word : {0}", VoiceModel.chtWord);
                }
                else
                {
                    result.Message = Localization.TrandlateMessage(Err.SaveOrCreateDataGoProblem);
                    Log.Debug("Create Voice data failed, Chinese Word : {0}", VoiceModel.chtWord);
                }
            }
            return Json(result, JsonRequestBehavior.DenyGet);
        }

        [HttpPost]
        public JsonResult Search(int? page, string searchkey, int categorySn)
        {
            int iPage = 1;
            if (page.HasValue)
            {
                iPage = int.Parse(page.Value.ToString());
            }
            searchkey = (string.IsNullOrEmpty(searchkey)) ? "" : searchkey;
            DbTableVoice odb = new DbTableVoice();
            Paging pg = new Paging()
            {
                pageSize = AppConfigManager.SystemSetting.UsersPageingSize,
                currentPage = iPage
            };
            DBSortingPara dbsp = new DBSortingPara();
            List<KeyValuePair<string, string>> paras = new List<KeyValuePair<string, string>>() { };
            paras.Add(new KeyValuePair<string, string>("chtWord", searchkey));
            paras.Add(new KeyValuePair<string, string>("categorySn", categorySn.ToString()));
            dbsp.AddSortingItem("SortingWeight", SortingType.ASC);

            VoiceListing bl = new VoiceListing();
            try
            {
                List<DbModelVoice> listData = odb.getAllData(ref pg, paras, dbsp);
                if (listData.Count > 0)
                {
                    bl.Result = ReturnCode.Success;
                    bl.listbl = new List<FormVoiceModel>();
                    bl.totalPages = pg.maxPage;

                    bl.listbl = listData.Select(x => new FormVoiceModel()
                    {
                        sn = x.sn,
                        chtWord = x.chtWord,
                        descript = StringHelper.ReplaceBreakLineToBR(x.descript),
                        example = StringHelper.ReplaceBreakLineToBR(x.example),
                        status = x.status,
                        voiceWord = x.voiceWord,
                        SortingWeight = x.SortingWeight
                    }).ToList();
                }
                else
                {
                    bl.Message = Localization.TrandlateMessage(Msg.ThereAreNoDateFound);
                    bl.Result = ReturnCode.SuccessWithNoData;
                }
            }
            catch (Exception ex)
            {
                bl.setException(ex, "VoiceService_Search");
            }
            return Json(bl, JsonRequestBehavior.DenyGet);
        }

        [HttpPost]
        public JsonResult Delete(int sn)
        {
            DbTableVoice o = new DbTableVoice();
            ResultBase result = new ResultBase();
            //check the user is exist.
            if (o.DeleteDataBySn(sn))
            {
                //Delete old file.
                DeleteConventedWavFile(sn);
                result.Result = ReturnCode.Success;
                result.Message = Localization.TrandlateMessage(Msg.DeleteSuccess);
            }
            else
            {
                result.Message = Localization.TrandlateMessage(Err.DeleteDataFailed);
            }
            return Json(result, JsonRequestBehavior.DenyGet);
        }

        [HttpPost]
        public JsonResult Update(int sn, string chtWord, string descript, string example, string voiceWord, int categorySn)
        {
            DbModelVoice model = new DbModelVoice()
            {
                sn = sn,
                chtWord = chtWord,
                descript = descript,
                example = example,
                voiceWord = voiceWord,
                //status = 0,
                CategorySn = categorySn
            };
            DbTableVoice o = new DbTableVoice();
            ResultBase result = new ResultBase();
            //check the user is exist.
            DbModelVoice dbmodel = o.getDataBySn(sn);
            if (dbmodel.sn > 0)
            {
                //Get all data.
                DbModelVoice oldDdata = o.getDataBySn(sn);
                if (string.Compare(oldDdata.voiceWord, model.voiceWord, true) == 0)
                {
                    model.status = oldDdata.status;
                }
                else
                {
                    //Delete old file.
                    DeleteConventedWavFile(model.sn);
                    model.status = 0;
                }
                if (o.updateDataBySN(model))
                {
                    result.Result = ReturnCode.Success;
                    result.Message = Localization.TrandlateMessage(Msg.UpdateVoiceDataSuccess);
                }
                else
                {
                    result.Message = Localization.TrandlateMessage(Err.SaveOrCreateDataGoProblem);
                }
            }
            else
            {
                result.Message = Localization.TrandlateMessage(Err.DataNotExistUpdateFailed);
            }
            return Json(result, JsonRequestBehavior.DenyGet);
        }

        private void DeleteConventedWavFile(int sn)
        {
            string filename = string.Format("s{0}.wav", sn);
            System.IO.File.Delete(Server.MapPath(".\\..\\..\\App_Data\\" + filename));
        }

        public JsonResult ReSorting(int SortingFrom, int SortingTo, int VoiceSn, int NewSortingID)
        {
            DbTableVoice odb = new DbTableVoice();
            odb.ReSortingOrdering(SortingFrom, SortingTo, VoiceSn, NewSortingID);
            return Json(null);
        }



        //VoiceConvert
        [HttpPost]
        public JsonResult VoiceConvert(int sn)
        {
            ResultBase result = new ResultBase();
            //Get vocie information
            DbTableVoice odb = new DbTableVoice();
            DbModelVoice modle = odb.getDataBySn(sn);

            string filename = string.Format("s{0}.wav", modle.sn);
            string saveToFile = Server.MapPath(".\\..\\..\\App_Data\\" + filename);
            bool canConvert = VoiceConverter.CreateVoiceFile(modle.voiceWord, saveToFile);

            if (canConvert)
            {
                //Update Status to 1
                modle.status = 1;
                odb.updateDataBySN(modle);
                result.Result = ReturnCode.Success;
                result.Message = "Convert to wav file success.";
            }
            else
            {
                result.setException(Err.ConvertVoiceFailed, "VoiceConvert");
            }

            return Json(result, JsonRequestBehavior.DenyGet);
        }

        #region Category
        [HttpPost]
        public JsonResult SearchCategory()
        {
            DbTableCategoryVoice odb = new DbTableCategoryVoice();
            CategoryVoiceListing bl = new CategoryVoiceListing();
            try
            {
                List<DbModelCategoryVoice> listData = odb.getAllData();
                if (listData.Count > 0)
                {
                    bl.Result = ReturnCode.Success;
                    bl.listbl = new List<DbModelCategoryVoice>();
                    foreach (DbModelCategoryVoice dmb in listData)
                    {
                        bl.listbl.Add(new DbModelCategoryVoice()
                        {
                            sn = dmb.sn,
                            Category = dmb.Category
                        });
                    }
                }
                else
                {
                    bl.Message = Localization.TrandlateMessage(Msg.ThereAreNoDateFound);
                    bl.Result = ReturnCode.SuccessWithNoData;
                }
            }
            catch (Exception ex)
            {
                bl.setException(ex, "VoiceService_SearchCategory");
            }
            return Json(bl, JsonRequestBehavior.DenyGet);
        }

        // GET: /VoiceService/
        [HttpPost]
        public JsonResult CreateVoiceCategory(string category)
        {
            DbTableCategoryVoice o = new DbTableCategoryVoice();
            ResultBase result = new ResultBase();

            DbModelCategoryVoice VoiceModel = new DbModelCategoryVoice()
            {
                sn = 0,
                Category = category
            };

            if (o.CheckCategoryIsExist(VoiceModel.Category))
            {
                result.Message = Localization.TrandlateMessage(Err.CategoryAlreayExist);
            }
            else
            {
                if (o.createData(VoiceModel))
                {
                    result.Message = Localization.TrandlateMessage(Msg.CreateVoiceDataSuccess);
                    result.Result = ReturnCode.Success;
                    Log.Debug("Create Voice Category data success, Category: {0}", VoiceModel.Category);
                }
                else
                {
                    result.Message = Localization.TrandlateMessage(Err.SaveOrCreateDataGoProblem);
                    Log.Debug("Create Voice Category data failed, Category: {0}", VoiceModel.Category);
                }
            }
            return Json(result, JsonRequestBehavior.DenyGet);
        }

        [HttpPost]
        public JsonResult DeleteCategory(int sn)
        {
            DbTableCategoryVoice o = new DbTableCategoryVoice();
            ResultBase result = new ResultBase();
            //check the user is exist.
            if (o.DeleteDataBySn(sn))
            {
                result.Result = ReturnCode.Success;
                result.Message = Localization.TrandlateMessage(Msg.DeleteSuccess);
            }
            else
            {
                result.Message = Localization.TrandlateMessage(Err.DeleteDataFailed);
            }
            return Json(result, JsonRequestBehavior.DenyGet);
        }

        [HttpPost]
        public JsonResult UpdateCategory(int sn, string category)
        {
            DbModelCategoryVoice model = new DbModelCategoryVoice()
            {
                sn = sn,
                Category = category
            };
            DbTableCategoryVoice o = new DbTableCategoryVoice();
            ResultBase result = new ResultBase();

            DbModelCategoryVoice dbmodel = o.getDataBySn(sn);
            if (dbmodel.sn > 0)
            {
                if (o.updateDataBySN(model))
                {
                    result.Result = ReturnCode.Success;
                    result.Message = Localization.TrandlateMessage(Msg.UpdateVoiceDataSuccess);
                }
                else
                {
                    result.Message = string.Format("The same Category ({0})is exist.", category);
                }
            }
            else
            {
                result.Message = Localization.TrandlateMessage(Err.DataNotExistUpdateFailed);
            }
            return Json(result, JsonRequestBehavior.DenyGet);
        }
        #endregion


    }
}
